<template>
  <view class="payApply-page">
    <view class="form-view">
      <u-form :model="form" ref="uForm" class="form-con">
        <u-form-item label="提现方式" label-width="180">
          <text class="fs-32 col-6">{{ payType }}</text>
        </u-form-item>
        <u-form-item label="到账姓名" label-width="180">
          <text class="fs-32 col-6">{{ userData.realName || "--" }}</text>
        </u-form-item>
        <u-form-item label="到账账户" label-width="180">
          <text class="fs-32 col-6">{{
            (userData.arrivalAccount || "") | arrAcc
          }}</text>
        </u-form-item>
        <u-form-item label="结算类型" label-width="180">
          <text class="fs-32 col-6">{{ form.type }}</text>
        </u-form-item>
        <u-form-item label="提现金额" label-width="180" prop="num">
          <text v-if="form.num" class="tag-view">{{ form.cashTypeEl }}</text>
          <u-input
            type="digit"
            v-model="form.num"
            :clearable="false"
            placeholder="请输入金额"
            @input="changeNum"
          />
          <u-button class="num-btn" hover-class="none" slot="right" @click="allWithdrawable"
            >全部提现</u-button
          >
        </u-form-item>
        <view
          :class="type === 4 ? 'allNum col-9 fs-24 line' : 'allNum col-9 fs-24'"
        >
          <text class="note" v-if="(type === 2 || type === 3) && form.num">
            {{ rateInfo }}
          </text>
          <text class="note" v-if="type === 4 || type === 5">
            因所在城市、银行不同需收取相关费用，请以实际到账为准。
          </text>
          <text class="note" v-if="type === 1">
            因地区和汇率的不同，请以实际到账为准。
          </text>
        </view>

        <u-form-item v-if="type === 4" label="上传凭证" label-width="180">
          <text class="num-btn upfile-view" @click="beforeAvatarUpload">{{
            form.fileName
          }}</text>
        </u-form-item>

        <view v-if="type === 4" class="allNum col-9 fs-24">
          <text class="note"
            >上传近三个月社保证明、学生证或退休证，大小3M，格式jpg。</text
          >
        </view>
      </u-form>
    </view>

    <!-- 协议（51社保，云账户） -->
    <view class="agree-view" v-if="type === 2 || type === 3">
      <u-checkbox
        v-model="checked"
        active-color="#19B1B8"
        size="28"
        @change="checkboxChange"
      >
        <text class="col-9 fs-24"> 阅读并同意 </text>
        <navigator class="go-to-new fs-24" :url="agreement.url">
          {{ agreement.name }}
        </navigator>
        <text class="col-9 fs-24"> ，接收信息尽快签约提现。 </text>
      </u-checkbox>
    </view>
    <!-- 校企合作 -->
    <view class="agree-view" v-if="type === 5">
      <view class="col-9 fs-24 txt-view">
        <text class="txt-label">发票抬头：</text>
        <text>四川语言桥信息技术有限公司</text>
      </view>
      <view class="col-9 fs-24 txt-view">
        <text class="txt-label">税号：</text>
        <text>91510100686315575Y</text>
      </view>
      <view class="col-9 fs-24 txt-view">
        <text class="txt-label">邮寄地址：</text>
        <text>
          中国（四川）自由贸易试验区成都高新区天府大道北段1288号1幢1单元801、802、803号</text
        >
      </view>
    </view>
    <!-- PayPal、国外银行、非全日制 -->
    <view class="agree-view" v-if="type === 1 || type === 4"></view>
    <!-- 提交按钮 -->
    <button class="pay-btn" @click="subPayInfo" :disabled="!disabled">
      提交
    </button>

    <!-- 弹框 -->
    <payModal
      @modalPwd="getModalPwd"
      :show="show"
      :toModalData="toModalData"
      :cashTypeEl="form.cashTypeEl"
    ></payModal>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import payModal from "./components/payModal";
import { baseURL } from "@/config/api-config.js";
import { mapState } from "vuex";
import {
  getRateAndTaxation,
  getAccountAmount,
  getCurrentCashoutInfo,
} from "@/api/user";
export default {
  components: {
    payModal,
  },

  data() {
    return {
      form: {
        way: "",
        name: "",
        account: "",
        type: "",
        num: "",
        cashTypeEl: "￥",
        fileName: "点击上传",
      },
      rules: {
        num: [
          {
            required: true,
            message: "请输入金额",
            trigger: ["change", "blur"],
          },
        ],
      }, //金额验证

      type: 1, //提现方式 type：1、paypal和国外银行卡， 2、社保51，3、云账户，4、非全日制，5、校企合作
      result: "", //结算类型
      cashTypeEl: {}, //货币类型
      agreement: {
        name: "《协议》",
        url: "/pages/user/agreement/yun/index",
      },
      checked: false, //协议勾选
      disabled: false, //提交按钮禁用
      withdrawableNum: 0, //可提现金额

      userData: {}, //用户账户信息
      rateData: {}, //税率税额
      rateInfo: "", //税收展示
      toModalData: {},
      show: false, //弹框
    };
  },
  computed: {
    ...mapState({
      userCode: (state) => state.userData["userCode"],
    }),
    payType: function () {
      if (this.type === 1) {
        if (this.result === "paypal") {
          return "Paypal";
        } else {
          return "国外银行卡";
        }
      } else {
        return "国内银行卡";
      }
    },
  },
  methods: {
    // 上传凭证
    beforeAvatarUpload() {
      console.log("上传图片1")
      uni.chooseImage({
        count: 1,
        success: (chooseImageRes) => {
          console.log("上传图片2")
          const tempFilePaths = chooseImageRes.tempFilePaths;
          console.log("上传图片3",chooseImageRes)
          //上传图片大小限制
          if (chooseImageRes.tempFiles[0].size > 3 * 1024 * 1000) {
            this.$refs.uToast.show({
              title: "图片大小不能超过3MB",
              type: "warning",
            });
            return null;
          }
          const imgType = chooseImageRes.tempFiles[0].path.split(".")[1];
          if (imgType != "jpeg" && imgType != "jpg") {
            this.$refs.uToast.show({
              title: "图片格式必须为jpg",
              type: "warning",
            });
            return null;
          }
          uni.showLoading({
            title: "上传中...",
            mask: true,
          });
          console.log("上传图片5",tempFilePaths[0])
          uni.uploadFile({
            url: baseURL + "/rm/financeNew/uploadCredential",
            filePath: tempFilePaths[0],
            name: "multipartFile",
            success: (uploadFileRes) => {
              console.log("上传图片4",uploadFileRes)
              this.toModalData.fileUrls = JSON.parse(uploadFileRes.data).data;
              // console.log(this.toModalData.fileUrls);
              let fileName = JSON.parse(uploadFileRes.data)
                .data.split("/")
                .slice(-1)[0];
              if (fileName.length > 28) {
                this.form.fileName =
                  fileName.slice(0, 15) + "..." + fileName.slice(-10);
              } else {
                this.form.fileName = fileName;
              }
            },
            fail: () => {
              uni.hideLoading();
              setTimeout(() => {
                this.$refs.uToast.show({
                  title: "上传失败",
                  type: "error",
                });
              }, 1000);
            },
            complete: () => {
              setTimeout(() => {
                uni.hideLoading();
              }, 500);
            },
          });
        },
      });
    },
    // 弹框数据
    getModalPwd(e) {
      this.show = e;
    },
    // 全部提现
    allWithdrawable() {
      // console.log(this.withdrawableNum);
      this.form.num = String(this.withdrawableNum);
      this.getRateAndTaxation(this.form.num);
    },
    // 输入金额获取税率
    getRateAndTaxation(num) {
      let data = {
        cashWithDrawalBalance: num,
        payType: this.result,
      };
      getRateAndTaxation(data).then((res) => {
        if (res.message === "success") {
          let data = res.data;
          if (data.payType === "社保51" || data.payType === "云账户") {
            this.rateData = data;
            this.rateInfo =
              "平台代缴￥" +
              data.taxation +
              "税费（费率：" +
              data.rate * 100 +
              "%）";
          } else {
            this.rateData = data;
            this.rateInfo = data.message;
          }
        } else {
          this.$refs.uToast.show({
            title: res.message,
            type: "error",
          });
        }
      });
    },
    //input监听
    changeNum(e) {
      setTimeout(() => {
        if (this.form.num) {
          if (
            this.form.num.split(".")[1] &&
            this.form.num.split(".")[1].length > 2
          ) {
            this.form.num =
              this.form.num.split(".")[0] +
              "." +
              this.form.num.split(".")[1].slice(0, 2);
            this.$refs.uToast.show({
              title: "只允许输入小数点后两位哟~",
              type: "warning",
            });
          }
          // if (this.form.num.split(".")[1].length > 2) {
          //   this.form.num =
          //     this.form.num.split(".")[0] +
          //     "." +
          //     this.form.num.split(".")[1].slice(0, 2);
          //   const reg = /^[0-9]+(.[0-9]{1,2})?$/; //保留一到两位小数的正数
          //   if (!reg.test(this.form.num)) {
          //     //判断输入为首位非零的正实数
          //     this.$refs.uToast.show({
          //       title: "请输入正确的金额",
          //       type: "warning",
          //     });
          //     return null;
          //   }
          // }

          if (this.form.num > this.withdrawableNum) {
            this.allWithdrawable();
            this.$refs.uToast.show({
              title: "最多可提现" + this.withdrawableNum,
              type: "warning",
            });
          } else {
            this.getRateAndTaxation(this.form.num);
          }
        }
      }, 1000);
    },
    // 获取可提取金额
    getAccountAmount() {
      getAccountAmount(this.userCode).then((res) => {
        if (res.message === "success") {
          const data = res.data;
          // console.log(data);
          if (data.cNY_Balance && this.cashTypeEl === "CNY") {
            this.withdrawableNum = Number(data.cNY_Withdrawable);
            this.toModalData.currencyCode = "CNY";
            this.toModalData.currencyName = "人民币";
          }
          if (data.uSD_Balance && this.cashTypeEl === "USD") {
            this.withdrawableNum = Number(data.uSD_Withdrawable);
            this.toModalData.currencyCode = "USD";
            this.toModalData.currencyName = "美元";
          }
          if (data.eUR_Balance && this.cashTypeEl === "EUR") {
            this.withdrawableNum = Number(data.eUR_Withdrawable);
            this.toModalData.currencyCode = "EUR";
            this.toModalData.currencyName = "欧元";
          }
          if (data.gBP_Balance && this.cashTypeEl === "GBP") {
            this.withdrawableNum = Number(data.gBP_Withdrawable);
            this.toModalData.currencyCode = "GBP";
            this.toModalData.currencyName = "英镑";
          }
        } else {
          this.$refs.uToast.show({
            title: res.message,
            type: "error",
          });
        }
      });
    },
    // 协议勾选
    checkboxChange(e) {
      this.disabled = e.value;
    },
    // 提交
    subPayInfo() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (this.type === 4 && this.form.fileName === "点击上传") {
            this.$refs.uToast.show({
              title: "请上传凭证",
              type: "warning",
            });
            return null;
          }
          if (this.form.num <= 0) {
            this.$refs.uToast.show({
              title: "提现金额必须大于0",
              type: "warning",
            });
            return null;
          }
          this.toModalData.arrivalAccount = this.userData.arrivalAccount;
          // this.toModalData.taxation = this.rateData.taxation;
          this.toModalData.num = this.form.num;
          this.toModalData.payType = this.type === 1 ? this.result : "银行卡"; //提现类型：银行卡，paypal，国外银行
          this.toModalData.settleType = this.result; //结算类型：paypal，51社保，云账户等
          this.$store.commit("setPayModalData", this.toModalData);
          console.log("验证通过=", this.toModalData, this.result);
          this.show = true;
        } else {
          console.log("验证失败");
        }
      });
    },
    // 获取页面参数
    getPageInfo() {
      let routes = getCurrentPages(), // 获取当前打开过的页面路由数组
        curParam = routes[routes.length - 1].options; //获取路由参数
      this.type = Number(curParam.type);
      this.result = decodeURIComponent(curParam.result);
      // console.log(curParam);
      this.cashTypeEl = curParam.cashTypeEl;
      switch (this.cashTypeEl) {
        case "CNY":
          this.form.cashTypeEl = "￥";
          break;
        case "USD":
          this.form.cashTypeEl = "$";
          break;
        case "EUR":
          this.form.cashTypeEl = "€";
          break;
        case "GBP":
          this.form.cashTypeEl = "￡";
          break;
      }
      switch (this.type) {
        case 1:
          this.form.type = this.result;
          this.disabled = true;
          break;
        case 2:
          this.form.type = "经营所得";
          this.agreement.name = "《协议》";
          this.agreement.url = "/pages/user/agreement/index";
          break;
        case 3:
          this.form.type = "经营所得";
          break;
        case 4:
          this.form.type = "非全日制";
          this.disabled = true;
          break;
        case 5:
          this.form.type = "校企合作";
          this.disabled = true;
          break;
      }
      let data = {
        userCode: this.userCode,
        payType: this.type === 1 ? this.result : "银行卡",
      };
      getCurrentCashoutInfo(data).then((res) => {
        if (res.message === "success") {
          this.userData = res.data;
        } else {
          this.$refs.uToast.show({
            title: res.message,
            type: "error",
          });
        }
      });
    },
  },
  onShow() {
    this.getPageInfo();
    this.getAccountAmount();
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss">
.payApply-page {
  padding-top: 20rpx;
  /deep/.u-form-item {
    font-size: 32rpx;
    color: #000;
  }
  /deep/.u-btn:after {
    border: none;
  }
  /deep/.u-hairline-border.data-v-3bf2dba7:after {
    border: none;
  }
  /deep/.u-btn--default.data-v-3bf2dba7 {
    color: $base-color;
  }
  /deep/.u-input__input {
    font-size: 32rpx;
    color: #000;
  }
  /deep/.u-mode-center-box {
    width: 80% !important;
  }
  /deep/.u-checkbox__label {
    position: relative;
    top: -2rpx;
  }
  /deep/.code-area {
    .dot {
      line-height: 32rpx !important;
    }
    .item {
      line-height: 0 !important;
    }
  }
  // /deep/.u-default-hover {
  //   background-color: transparent !important;
  //   color: rgba($color: $base-color, $alpha: 0.75) !important;
  //   border-color: transparent !important;
  // }
  // 表单
  /deep/.u-form-item.data-v-5e7216f1 {
    font-size: 32rpx !important;
    line-height: 60rpx !important;
  }
  /deep/.u-input.data-v-fdbb9fe6 {
    input {
      min-height: 60rpx !important;
    }
  }
  .form-view {
    padding-left: 24rpx;
    background-color: #fff;
    .form-con {
      .allNum {
        margin-left: 180rpx;
        padding: 12rpx 40rpx 12rpx 0;
        // .shui {
        //   line-height: 84rpx;
        // }
        .note {
          line-height: 36rpx;
        }
      }
      .line {
        border-bottom: 1px solid #e4e7ed;
      }
      .num-btn {
        color: $base-color;
        font-size: 32rpx;
        height: 70rpx !important;
        line-height: 70rpx !important;
        &:active {
          color: rgba($color: $base-color, $alpha: 0.75);
        }
      }
      .upfile-view {
        width: 510rpx;
      }
    }
    .tag-view {
      float: left;
    }
  }
  .agree-view {
    padding: 0 24rpx;
    margin: 40rpx 0 60rpx 0;
    .go-to-new {
      color: $base-color;
      display: inline-block;
    }
    .txt-view {
      display: flex;
      flex-direction: row;
      justify-content: initial;
      text {
        width: 566rpx;
        line-height: 40rpx;
      }
      .txt-label {
        width: 124rpx !important;
      }
    }
  }
}
</style>
